<?php
namespace Admin\Service;

/**
 * 退款功能后台服务
 */

class RefundService
{
    const REASON_PARAM_KEY = 'REFUND_REASON';
    const PAY_PARAM_KEY = 'PAY_WAY';
    const WAIBU_PARAM_KEY = 'WAIBU_TOUSU';

    protected $m_res = array('rcode'=>0,'data'=>NULL,'msg'=>'500 Internal Error');

    //根据系统参数表，返回配置的退款原因
    public function reasons($sys_key){
        $MParam = D('Admin/SysParam');
        $MParamDetail = D('Admin/SysParamDetail');
        $wheres = array();
        $wheres['key_name'] = array('eq', $sys_key );
        $dparam = $MParam->where( $wheres )->find();
        if( !$dparam ){
            return FALSE;
        }
        else{
            $whered = array();
            $whered['sys_param_id'] = array('eq', $dparam['sys_param_id']);
            $detail = $MParamDetail->where( $whered )->order("detail_order asc")->select();
            if( !$detail ) return FALSE;
            $data = array();
            $item = array();
            foreach( $detail as $dv ){
                $item['name'] = $dv['detail_name'];
                $item['value'] = $dv['detail_value'];
                $item['id'] = $dv['sys_param_detail_id'];
                $data[] = $item;
            }
            return $data;
        }
    }

    public function add( $add_data,$add_delivery,$add_refund )
    {
        $res = $this->m_res;

        if( !$add_data ){
            $res['msg'] = L('PARAM_WRONG');
        }
        else{
            $Mdo = D('Admin/Refund');
            //验证关联客户、销售、分公司
            // if( !$add_data['customer_id'] || !$add_data['sales_id'] || !$add_data['sales_subcompany']){
            //     $res['msg'] = "关联客户、销售、分公司不能为空";
            //     return $res;
            // }
            //验证退款信息以及退款金额
            if( !$add_data['pay_mount'] || !$add_data['payee_name'] || !$add_data['payee_account'] || !$add_data['payee_way'] ){
                $res['msg'] = "客户退款金额以及付款信息不能为空";
                return $res;
            }
            //验证客户合同、发票、投诉状态
            if( !$add_data['contract_status'] || !$add_data['invoice_status'] || !$add_data['complain_status'] ){
                $res['msg'] = "客户合同、发票以及投诉状态不能为空";
            }
            //验证客户退款信息
            if( !isset( $add_data['reason_id'])  || NULL === $add_data['reason_id'] ){
                $res['msg'] = "客户退款原因不能为空";
                return $res;
            }

            $add_data['create_time'] = date('Y-m-d H:i:s');
            $add_data['is_delete'] = 0;
            $add_data['status'] = \Admin\Model\RefundModel::STATUS_INIT;

            $ret = $Mdo->data( $add_data )->add();
            if( $ret ){
                foreach($add_delivery as &$value) {
                    $value['source_id'] = $ret;
                    M('delivery')->add($value);
                }
                foreach($add_refund as &$value) {
                    $value['refund_id'] = $ret;
                    M('pays','refund_')->add($value);
                }

                $res['rcode'] = 1;
                $res['msg'] = 'OK';
                $res['data'] = $ret;
            }else{
                $res['msg'] = "保存数据失败，错误信息：".$Mdo->getError();
            }
        }

        return $res;
    }

    //退款申请信息编辑
    public function edit( $refund_id, $_update ,$refund,$delivery)
    {
        $res = $this->m_res;
        $wheres = array();
        $Mdo = D('Admin/Refund');
        $wheres['refund_id'] = array('eq', $refund_id );

        $data = $Mdo->where( $wheres )->find();
        if( !$data )
            $res['msg'] = L('NO_DATA');
        else if( !$_update )
            $res['msg'] = L('PARAM_WRONG');
        else{
            // if( $data['status'] ==  \Admin\Model\RefundModel::STATUS_INIT ){
                //验证关联客户、销售、分公司
                // if( !$_update['sales_id'] || !$_update['sales_subcompany']){
                //     $res['msg'] = "销售、分公司不能为空";
                //     return $res;
                // }
                //验证退款信息以及退款金额
                if( !$_update['pay_mount'] || !$_update['payee_name'] || !$_update['payee_account'] || !$_update['payee_way'] ){
                    $res['d'] = $_update;
                    $res['msg'] = "客户退款金额以及付款信息不能为空";
                    return $res;
                }
                if(isset($_update['refund_id']) )
                    unset( $_update['refund_id']);
                /*更新退款表*/
                $Mdo->where( $wheres )->save( $_update );
                $rid = $Mdo->getError() ? FALSE:TRUE;
                /*更新退款流水表*/
                $refundID = '';
                foreach($refund as &$value) {
                    $data = $value;
                    unset($data['refund_pays_id']);
                    $refundID = M('pays','refund_')->where("refund_pays_id=%d",$value['refund_pays_id'])->save($data);
                }
                /*更新邮寄记录*/
                $deliveryID = '';
                foreach($delivery as &$value) {
                    $data = $value;
                    /**
                     * BUG fix: mysql datetime error 1292
                     * 
                    */
                    if (isset($data['send_time']) && !$data['send_time']) {
                        $data['send_time'] = NULL;
                    }
                    if(isset($value['delivery_id'])){
                        unset($data['delivery_id']);
                        $deliveryID = M('delivery')->where("delivery_id=%d",$value['delivery_id'])->save($data);
                    }else {
                        $value['source_id'] = $refund_id;
                        $value['source_type'] = 3;
                        if($_update['sales_id'])    $value['sales_id'] = $_update['sales_id'];
                        if($_update['customer_id'])    $value['customer_id'] = $_update['customer_id'];
                        $value['status'] = 10;
                        $deliveryID = M('delivery')->add($value);
                    }
                }
                if( $rid || $refundID || $deliveryID){
                    $res['rcode'] = 1;
                    $res['data'] = $rid;
                    $res['msg'] = L('DATA_SAVE_OK');
                }
                else{
                    $res['msg'] = L('DATA_SAVE_ERR');
                }
            // }
            // else{
            //     $res['msg'] = "该退款申请无法编辑";
            // }
        }
        return $res;
    }

    //根据输入的客户名或者电话号码查询客户信息
    public function customer( $data )
    {
        $res = $this->m_res;
        if( !$data ){
            $res['msg'] = L('PARAM_WRONG');
        }
        else{
            $MCustomer = D('Admin/Customer');
            $wheres = array();
            if( preg_match('#^1[0-9]{10}$#', $data) ){
                $wheres['customer.phone'] = array('eq', $data);
            }
            else
                // $wheres['customer.nickname'] = array('like', '%'.$data.'%');
                $wheres['customer.nickname'] = $data;

            $udata = M()->field('customer.*,user.nickname as sales_name,f.user_id as sales_manager,f.nickname as manager_name')
                                ->table('customer')
                                ->join("LEFT JOIN user on user.user_id=customer.sales_person")
                                ->join("LEFT JOIN user f on f.user_id=customer.sales_manager")
                                ->where( $wheres )
                                ->select();
            if( !$udata ){
                $res['msg'] = "查找客户不存在";
            }
            else{
                if( count( $udata) > 1 ){
                    $res['rcode'] = 2;
                    // $res['msg'] = "匹配到多个客户信息";
                    $res['msg'] = $udata;
                }
                else{
                    $res['rcode'] = 1;
                    $res['data'] = $udata[0];
                    //获取客户付款总金额
                    $MCon = D('Admin/Contract');
                    $whereC = array();
                    $whereC['a.audit_res'] = 1;
                    $whereC['a.record_status'] = 1;
                    $whereC['a.pay_type'] = array('NEQ',3);
                    $whereC['a.customer_id'] = array('eq', $res['data']['customer_id']);
                    $dPay = M() ->field("a.payrecord_id,a.pay_id,a.pay_mount,a.refund_mount as refunded,a.pay_time,b.nickname as sales_name,c.sector_name as company_name,d.nickname as manager_name")
                                ->table('pay_record as a')
                                ->join('user as b on b.user_id = a.sales_person','LEFT')
                                ->join('sector as c on c.sector_id = a.sales_sub_company','LEFT')
                                ->join('user as d on d.user_id = a.sales_manager','LEFT')
                                ->where($whereC)
                                ->select();

                    foreach($dPay as &$value) {
                        $value['will_refund'] = 0;
                        $value['is_refund'] = true;
                        if(!$value['refunded']) {
                            $value['refunded'] = 0;
                        }
                    }
                    $res['contracts'] = $dPay;
                }
            }
        }
        return $res;
    }

    //根据客户ID查询客户关联的合同信息
    public function contract( $customer_id, $size = FALSE )
    {
        $res = $this->m_res;
        $wheres = array();
        $MCon = D('Admin/Contract');
        $wheres['contract.customer_id'] = array('eq', $customer_id);
        $dCons = $MCon->field("contract.start_time,contract.end_time,contract.state,contract.mount,p.name as pname,u.nickname as sales_name")
                      ->join("LEFT JOIN product p on p.product_id=contract.product_id")
                      ->join("LEFT JOIN user u on u.user_id=contract.sales_person")
                      ->where( $wheres )
                      ->order("contract.create_time desc")
                      ->select();
        if( $dCons ){
            $res['rcode'] = 1;
            $res['msg'] = 'OK';
            $res['data'] = $dCons;
        }
        else
            $res['msg'] = "获取客户合同信息失败";

        return $res;
    }

    /**
     * 退款确认与取消申请
     * @param  int  $refund_id  退款申请ID
     * @param  int  $approve    批准审核或者拒绝通过
     * @param  array $extdata   合同、发票、投诉处理状态
     * @return array            array('rcode'=>'','data'=>'','msg'=>'')
     */
    public function confirm( $refund_id, $approve, $extdata ) {// approve: 0:拒绝通过;1:确认付款 
        $res = $this->m_res;
        $Mdo = D('Admin/Refund');

        $wheres = array();
        $wheres['refund_id'] = array('eq', $refund_id );
        $wheres['is_delete'] = array('neq', 1);
        $data = $Mdo->where( $wheres )->find();

        if( !$data ){
            $res['msg'] = L('NO_DATA');
        }
        else{
            if( \Admin\Model\RefundModel::STATUS_CANCEL == $data['status'] || \Admin\Model\RefundModel::STATUS_FAILED == $data['status'] || \Admin\Model\RefundModel::CAI_SUCCESS == $data['status']){
                $res['msg'] = "退款数据已经不能修改";
            }
            else{
                $dup = array();
                if( 0 == $approve ){ //申请失败
                    $dup['status'] = \Admin\Model\RefundModel::STATUS_FAILED;
                    if($extdata)    $dup = array_merge($extdata, $dup );
                    $Mdo->where( $wheres )->save( $dup );
                    $res['rcode'] = 1;
                }
                else if(1 == $approve){ //确认退款
                    $dup['status'] = \Admin\Model\RefundModel::FENG_SUCCESS;
                    if($extdata)    $dup = array_merge($extdata, $dup );
                    if( $Mdo->where( $wheres )->save( $dup )  ){
                        /*更改邮寄记录为确认邮寄*/
                        $data = array();
                        $data['status'] = 20;
                        $where = array();
                        $where['source_type'] = 3;
                        $where['source_id'] = $refund_id;
                        M('delivery')->where($where)->save($data);
                        $data_up = $Mdo->where( $wheres )->find();
                        $res['rcode'] = 1;
                        $res['msg'] = 'OK';
                        $res['data'] = 1;
                    }
                    else{
                        $res['msg'] = "退款处理失败";
                    }
                } else if(2 == $approve) { //取消退款
                    $dup['status'] = \Admin\Model\RefundModel::STATUS_CANCEL;
                    $Mdo->where( $wheres )->save( $dup );
                    $res['rcode'] = 1;
                }
            }
        }
        return $res;
    }

    //根据退款ID获取退款详情
    public function detail( $refund_id )
    {
        $Mdo = D('Admin/Refund');
        $wheres = array();
        $wheres['refund.refund_id'] = array('eq', $refund_id );
        $detail = $Mdo->field("refund.*,us.nickname as sales_name,ua.nickname as manager_name,s.sector_name as company,c.nickname as customer_name")
                    ->join("LEFT JOIN user us on us.user_id=refund.sales_id")
                    ->join("LEFT JOIN user ua on ua.user_id=refund.sales_manager")
                    ->join("LEFT JOIN sector s on s.sector_id=refund.sales_subcompany")
                    ->join("LEFT JOIN customer c on c.customer_id=refund.customer_id")
                    ->where( $wheres )
                    ->find();
        if( !$detail ){
            return false;
        }
        else{
            $detail['reason_name'] = '';
            // $_contract = $this->contract( $detail['customer_id'] );
            $whereD = array();
            $whereD['source_id'] = $refund_id;
            $whereD['source_type'] = 3;
            $delivery = M('delivery')->field("delivery_id,recipients,phone,address,delivery_num,send_way,send_time,remark")->where($whereD)->order('create_time desc')->select();
            $whereF = array();
            $whereF['a.refund_id'] = $refund_id;
            $whereF['b.audit_res'] = 1;
            $whereF['b.record_status'] = 1;
            $refund = M()->field("a.refund_pays_id,a.refund_id,a.pay_id,a.refund_mount,b.pay_mount,b.pay_time,c.nickname as sales_name,d.nickname as manager_name,e.sector_name as company_name,
                                    CASE WHEN b.refund_mount is null THEN 0
                                         ELSE b.refund_mount END AS pay_refund_mount
                            ")
                            ->table('refund_pays as a')
                            ->join('pay_record as b on b.pay_id = a.pay_id')
                            ->join('user as c on c.user_id = b.sales_person','LEFT')
                            ->join('user as d on d.user_id = b.sales_manager','LEFT')
                            ->join('sector as e on e.sector_id = b.sales_sub_company','LEFT')
                            ->where($whereF)
                            ->select();

            /*退款原因*/
            $dreasons = $this->reasons('REFUND_REASON');
            if( $dreasons ){
                foreach($dreasons as $vd ){
                    if($vd['id'] == $detail['reason_id'] )
                        $detail['reason_name'] = $vd['name'];
                }
            }
            /*外部投诉*/
            $dwaibu = $this->reasons('WAIBU_TOUSU');
            if( $dwaibu ){
                foreach($dwaibu as $vd ){
                    if($vd['id'] == $detail['waibu_tousu'] )
                        $detail['waibu_tousu_name'] = $vd['name'];
                }
            }
            $data = array();
            $detail['customer_phone'] = $detail['phone'];
            $data['detail'] = $detail;
            $data['delivery'] = $delivery;
            $data['refund'] = $refund;
            return $data;
        }
    }

    //根据退款ID删除记录
    public function delete( $refund_id )
    {
        $res = $this->m_res;
        $Mdo = D('Admin/Refund');
        $wheres = array();
        $wheres['refund_id'] = array('eq', $refund_id );
        $data = $Mdo->where( $wheres )->find();
        if( !$data ){
            $res['msg'] = L('DATA_DELETE_ERR');
        }
        else{
            $res['rcode'] = 1;
            $res['msg'] = L('DATA_DELETE_OK');
            if( $dta['is_delete'] ){
                $res['data'] = 0;
            }
            else{
                 $dup = array();
                $dup['is_delete'] = 1;
                $Mdo->where( $wheres )->save( $dup );
            }
        }

        return $res;
    }

    //根据退款申请ID取消申请
    public function cancel( $refund_id )
    {
        $res = $this->m_res;
        $wheres = array();
        $wheres['refund_id'] = array('eq', $refund_id );
        $wheres['is_delete'] = array('neq', 1);
        $Mdo = D('Admin/Refund');
        //
        $data = $Mdo->where( $wheres )->find();
        if( !$data ){
            $res['msg'] = L('NO_DATA');
        }
        else{
            $res['rcode'] = 1;
            if( \Admin\Model\RefundModel::STATUS_CANCEL == $data['status'] ){
                $res['rcode'] = 1;
                $res['data'] = 0;
                $res['msg'] = 'OK';
            }
            else if( \Admin\Model\RefundModel::STATUS_INIT == $data['status'] ){
                $dup = array();
                $dup['status'] = \Admin\Model\RefundModel::STATUS_CANCEL;
                $res['data'] = $Mdo->where( $wheres )->save( $dup );
                if( $res['data'] ){
                    $res['rcode'] = 1;
                    $res['msg'] = 'OK';
                }
                else{
                    $res['msg'] = "退款数据取消失败";
                }
            }
            else{
                $res['msg'] = '退款数据无法取消';
            }
        }
        return $res;
    }
}
